<script setup>
import SvgIcon from "@/components/icon/SvgIcon.vue";
import { ref, onMounted, watch, nextTick } from "vue";
import { useCompanyStore } from "@/stores/company";
import { getResourceStats } from "@/utils/meterUtils";

const companyStore = useCompanyStore();

const resourceItems = ref([
  {
    icon: "water",
    value: "0",
    unit: "m³",
    label: "本月用水量",
    colorClass: "text-blue",
    isLoading: true,
  },
  {
    icon: "electricity",
    value: "0",
    unit: "kWh",
    label: "本月用电量",
    colorClass: "text-yellow",
    isLoading: true,
  },
  {
    icon: "gas",
    value: "0",
    unit: "m³",
    label: "本月用气量",
    colorClass: "text-orange",
    isLoading: true,
  },
  {
    icon: "carbon",
    value: "0",
    unit: "t",
    label: "本月碳排放总量",
    colorClass: "text-green",
    isLoading: true,
  },
]);

// 更新单个资源项的数据和加载状态
const updateResourceItem = (type, value) => {
  const typeMap = {
    water: 0,
    electricity: 1,
    gas: 2,
    carbon: 3
  };

  const index = typeMap[type];
  if (index !== undefined) {
    // 使用 nextTick 确保 DOM 更新的正确时序
    nextTick(() => {
      resourceItems.value[index] = {
        ...resourceItems.value[index],
        value,
        isLoading: false
      };
    });
  }
};

// 获取并更新资源使用数据
const fetchResourceData = async () => {
  try {
    if (!companyStore.currentCompany?.id) return;

    // 重置所有项的加载状态
    resourceItems.value.forEach(item => {
      item.isLoading = true;
      item.value = "0"; // 重置值避免重影
    });

    await getResourceStats({
      range: "month",
      companyId: companyStore.currentCompany.id,
      onProgress: (type, value) => {
        updateResourceItem(type, value);
      }
    });
  } catch (error) {
    console.error("获取资源使用数据失败:", error);
    // 出错时将所有项的加载状态设为 false
    resourceItems.value.forEach(item => item.isLoading = false);
  }
};

// 监听公司变化
watch(
  () => companyStore.currentCompany,
  (newCompany) => {
    if (newCompany && newCompany.id) {
      fetchResourceData();
    }
  },
  { immediate: true }
);

// 组件挂载时获取数据
onMounted(() => {
  if (companyStore.currentCompany && companyStore.currentCompany.id) {
    fetchResourceData();
  }
});
</script>

<template>
  <el-card body-style="height: 100%;" class="resource-usage" shadow="always">
    <div class="card-container">
      <div class="resource-items-container">
        <div v-for="(item, index) in resourceItems" :key="item.label" class="resource-item"
          :class="{ 'with-divider': index < resourceItems.length - 1 }">
          <div class="resource-content">
            <SvgIcon class="resource-icon" size="45px" :icon="item.icon" />

            <!-- 修改：使用v-if而不是v-show，避免Safari的重叠问题 -->
            <div class="info" v-if="!item.isLoading">
              <div class="value">
                <AnimatedNumber size="medium" :suffix="item.unit" :value="parseFloat(item.value)" :duration="1000"
                  class="number" :key="`${item.label}-${item.value}`" />
              </div>
              <div class="label">{{ item.label }}</div>
            </div>

            <!-- 修改：骨架屏加载器，使用绝对定位避免重叠 -->
            <div v-if="item.isLoading" class="skeleton-loader">
              <div class="skeleton-value"></div>
              <div class="skeleton-label"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<style scoped>
.resource-usage {
  width: 100%;
  height: 100%;
  --card-padding: clamp(16px, 2vw, 24px);
  --icon-size: clamp(32px, 4vw, 45px);
  --title-size: clamp(13px, 1.5vw, 16px);
  --value-size: clamp(20px, 2.5vw, 28px);
  --label-size: clamp(12px, 1.4vw, 14px);
  --item-padding: clamp(16px, 3vw, 32px);
}

.card-container {
  display: flex;
  height: 100%;
  align-items: center;
  justify-content: center;
}

.resource-items-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: nowrap;
}

.with-divider {
  border-right: 1px solid var(--el-border-color);
}

.resource-item {
  display: flex;
  gap: 16px;
  align-items: center;
  height: clamp(80px, 10vh, 90px);
  width: 273px;
  min-width: 273px;
  position: relative;
}

.resource-content {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
  /* Safari 兼容性：确保正确的层叠上下文 */
  z-index: 1;
}

.resource-icon {
  margin-left: 50px;
  width: var(--icon-size);
  height: var(--icon-size);
  flex-shrink: 0;
  /* Safari 兼容性：防止图标被压缩 */
  z-index: 2;
}

.info {
  display: flex;
  flex-direction: column;
  margin-left: 16px;
  /* Safari 兼容性：移除transition，避免渲染问题 */
  opacity: 1;
  /* Safari 兼容性：确保正确的定位上下文 */
  position: relative;
  z-index: 3;
}

.value {
  display: flex;
  align-items: baseline;
  font-weight: bold;
  color: #303133;
  font-size: var(--value-size);
  /* Safari 兼容性：确保文本渲染稳定 */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.label {
  font-size: var(--label-size);
  margin-top: clamp(2px, 0.5vh, 4px);
  /* Safari 兼容性：确保文本渲染稳定 */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.skeleton-loader {
  /* Safari 兼容性：使用固定定位而不是绝对定位 */
  position: relative;
  margin-left: 16px;
  width: 150px;
  /* Safari 兼容性：移除transform，使用margin代替 */
  /* Safari 兼容性：移除transition，避免渲染问题 */
  z-index: 3;
}

.skeleton-value {
  height: 28px;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  /* Safari 兼容性：简化动画 */
  animation: loading 1.5s infinite linear;
  border-radius: 4px;
  margin-bottom: 8px;
  /* Safari 兼容性：添加will-change提升性能 */
  will-change: background-position;
}

.skeleton-label {
  height: 14px;
  width: 70%;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  /* Safari 兼容性：简化动画 */
  animation: loading 1.5s infinite linear;
  border-radius: 4px;
  /* Safari 兼容性：添加will-change提升性能 */
  will-change: background-position;
}

/* Safari 兼容性：简化关键帧动画 */
@keyframes loading {
  0% {
    background-position: 200% 0;
  }

  100% {
    background-position: -200% 0;
  }
}

/* Safari 兼容性：添加-webkit-前缀 */
@-webkit-keyframes loading {
  0% {
    background-position: 200% 0;
  }

  100% {
    background-position: -200% 0;
  }
}

@media screen and (max-width: 1600px) {
  .card-container {
    flex-direction: column;
    gap: var(--card-padding);
  }

  .resource-items-container {
    width: 100%;
    justify-content: center;
  }

  .resource-item {
    flex: 1;
    padding: 0;
    justify-content: center;
  }
}

@media screen and (max-width: 1200px) {
  .resource-items-container {
    flex-wrap: wrap;
    gap: var(--card-padding);
  }

  .resource-item {
    flex: 0 0 calc(50% - var(--card-padding));
    border-right: none;
    justify-content: center;
    width: 200px;
  }

  .info {
    min-width: 150px;
  }

  .with-divider {
    border-right: none;
  }
}

@media screen and (min-width: 1920px) {
  .resource-usage {
    --icon-size: 45px;
    --title-size: 16px;
    --value-size: 28px;
    --label-size: 14px;
    --item-padding: 32px;
  }
}

@media screen and (max-width: 768px) {
  .resource-item {
    flex: 0 0 100%;
  }
}
</style>